import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import Page from '../../components/Page';
import { Link } from 'react-router-dom'

import Button from '../../components/Button';
import bg_index from '../../assets/image/banner_Congress.png';
import bg_index_h5 from '../../assets/image/h5banner_Congress.png';
import LaunchCountdown from '../../components/LaunchCountdown';
import config, { voteDefinitions } from '../../config';
import Spacer from '../../components/Spacer';
import TokenSymbol from '../../components/TokenSymbol';
import Label from '../../components/Label';

import dui from '../../assets/image/dui.jpg';
import cuo from '../../assets/image/cuo.jpg';
import useCongressEarnedS from '../../hooks/useCongressEarnedS';
import useCongressEarnedV from '../../hooks/useCongressEarnedV';
import { getDisplayBalance } from '../../utils/formatBalance';
import useBalanceOf from '../../hooks/useBalanceOf';
import useBasisCash from '../../hooks/useBasisCash';
import useCongressBalance from '../../hooks/useCongressBalance';
import { BigNumber } from 'ethers';
import useHarvestV from '../../hooks/useHarvestV';
import useHarvestS from '../../hooks/useHarvestS';
import useApprove, { ApprovalState } from '../../hooks/useApprove';
import { useWallet } from 'use-wallet';
import { AddIcon, RemoveIcon } from '../../components/icons';
import IconButton from '../../components/IconButton';
import DepositModal from '../Bank/components/DepositModal';
import WithdrawModal from '../Bank/components/WithdrawModal';
import useModal from '../../hooks/useModal';
import useTokenBalance from '../../hooks/useTokenBalance';
import useStakedBalance from '../../hooks/useStakedBalance';
import { Bank, VoteInfo } from '../../basis-cash';
import useStake from '../../hooks/useStake';
import useWithdraw from '../../hooks/useWithdraw';
import useCongressDonate from '../../hooks/useCongressDonate';
import useStakeV from '../../hooks/useStakeV';
import useVotes from '../../hooks/useVotes';
import VoteCard from './components/VoteCard';

const Home: React.FC = () => {
  const basisCash = useBasisCash();
  const { account } = useWallet();
  
  const [votes, setVotes] = useState<VoteInfo[]>([]);

  const fetchPools = useCallback(async () => {
    const votes: VoteInfo[] = [];
    console.log('voteDefinitions', voteDefinitions);
    for (const voteInfo of Object.values(voteDefinitions)) {
      console.log('voteInfo.contract', voteInfo.contract);
      votes.push({
        ...voteInfo
      });
      console.log('voteInfo.contract', voteInfo.contract);
    }
    console.log('votes', votes);
    votes.sort((a, b) => (a.sort > b.sort ? 1 : -1));
    setVotes(votes);
  }, [basisCash, basisCash?.isUnlocked, setVotes]);

  useEffect(() => {
    if (basisCash) {
      fetchPools()
        .catch(err => console.error(`Failed to fetch pools: ${err.stack}`));
    }
  }, [basisCash, basisCash?.isUnlocked, fetchPools]);

  console.log('votes', votes);

  const earnedS = useCongressEarnedS();
  const earnedV = useCongressEarnedV();
  const balanceOf = useCongressBalance();
  //const earnedS = BigNumber.from(0);
  //const earnedV = BigNumber.from(0);
  //const balanceOf = BigNumber.from(0);

  const {onRewardV} = useHarvestV();
  const {onRewardS} = useHarvestS();

  const depositTokenName = 'SHARE';
  const bank: Bank = useMemo(() => { 
    return {name:'', contract: 'shareSplit', depositTokenName: 'SHARE', earnTokenName: 'SHARE', finished: false, address: basisCash?.contracts['shareSplit']?.address, sort: 0, depositToken: basisCash?.externalTokens[depositTokenName], earnToken: basisCash?.externalTokens[depositTokenName]};
  }, [basisCash, basisCash?.contracts['shareSplit'], basisCash?.externalTokens[depositTokenName]]);

  const [approveStatus, approve] = useApprove(basisCash?.externalTokens[depositTokenName], basisCash?.contracts['shareSplit']?.address);

  const tokenBalance = useTokenBalance(basisCash?.externalTokens[depositTokenName]);
  const stakedBalance = useStakedBalance('shareSplit');

  const { onStake } = useStake(bank);
  const { onWithdraw } = useWithdraw(bank);
  const { onDonate } = useCongressDonate(bank);

  const [onPresentDeposit, onDismissDeposit] = useModal(
    <DepositModal
      max={tokenBalance}
      decimals={bank.depositToken?.decimal}
      onConfirm={(amount) => {
        onStake(amount);
        onDismissDeposit();
      }}
      tokenName={bank.depositTokenName}
      fractionDigits={6}
    />,
  );

  const [onPresentWithdraw, onDismissWithdraw] = useModal(
    <WithdrawModal
      max={stakedBalance}
      decimals={bank.depositToken?.decimal}
      onConfirm={(amount) => {
        onWithdraw(amount);
        onDismissWithdraw();
      }}
      tokenName={bank.depositTokenName}
    />,
  );

  const vbank: Bank = useMemo(() => { 
    return {name:'', contract: 'shareSplit', depositTokenName: 'vSHARE', earnTokenName: 'vSHARE', finished: false, address: basisCash?.contracts['shareSplit']?.address, sort: 0, depositToken: basisCash?.externalTokens['vSHARE'], earnToken: basisCash?.externalTokens['vSHARE']};
  }, [basisCash, basisCash?.contracts['shareSplit'], basisCash?.externalTokens['vSHARE']]);

  const [approveVStatus, approveV] = useApprove(basisCash?.externalTokens['vSHARE'], basisCash?.contracts['shareSplit']?.address);
  const tokenBalanceV = useTokenBalance(basisCash?.externalTokens['vSHARE']);
  const { onStakeV } = useStakeV(vbank);

  console.log('approve', approveStatus + ' ' + approveVStatus);

  const [onPresentDepositV, onDismissDepositV] = useModal(
    <DepositModal
      max={tokenBalanceV}
      decimals={vbank.depositToken?.decimal}
      onConfirm={(amount) => {
        onStakeV(amount);
        onDismissDepositV();
      }}
      tokenName={vbank.depositTokenName}
      fractionDigits={6}
    />,
  );

  return (
    <Page>
      <StylehCont>
        <StyleDiv1>
          <img
            src={bg_index}
            alt='logo'
            style={{ width: '100%', height: 'auto' }}
          />
        </StyleDiv1>
        <StyleDiv2>
          <img
            src={bg_index_h5}
            alt='logo'
            style={{ width: '100%', height: 'auto' }}
          />
        </StyleDiv2>

        {!!account ? (
        <>
        <CardWrapper>
          <StyledCards>
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: '15px' }}>
              <TokenSymbol symbol="sSHARE" />
              <CardHeader>sSHARE</CardHeader>
            </div>
            <StyledCardSuperAccent>
              <CardSection>
                <StyledValue>{getDisplayBalance(earnedS)}</StyledValue>
                <Label text="sSHARE Earned" color={'#23223E'} />
              </CardSection>
            </StyledCardSuperAccent>
            {
            <div style={{ marginTop: 30 }}>
              <Button text="Settle" disabled={earnedS.eq(0)} onClick={onRewardS} />
            </div>
            }
          </StyledCards>

          <StyledCards>
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: '15px' }}>
              <TokenSymbol symbol="vSHARE" />
              <CardHeader>vSHARE</CardHeader>
            </div>
            <StyledCardSuperAccent2>
              <CardSection>
                <StyledValue>{getDisplayBalance(earnedV)}</StyledValue>
                <Label text="vSHARE Earned" color={'#23223E'} />
              </CardSection>
            </StyledCardSuperAccent2>
            {
            <div style={{ marginTop: 30 }}>
              {approveVStatus !== ApprovalState.APPROVED ? (
                <Button
                  disabled={
                    approveVStatus == ApprovalState.PENDING ||
                    approveVStatus == ApprovalState.UNKNOWN
                  }
                  onClick={approveV}
                  text={`Approve`}
                />
              ) : (
                <StyledCardActions>
                  <IconButton onClick={onRewardV} disabled={earnedV.eq(0)}>
                    <RemoveIcon />
                  </IconButton>
                  <StyledActionSpacer />
                  <IconButton
                    onClick={onPresentDepositV}
                  >
                    <AddIcon />
                  </IconButton>
                </StyledCardActions>
              )}
            </div>
            }
          </StyledCards>


          <StyledCards>
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: '15px' }}>
              <TokenSymbol symbol="SHARE" />
              <CardHeader>SHARE</CardHeader>
            </div>
            <StyledCardSuperAccent1>
              <CardSection>
                <StyledValue>{getDisplayBalance(balanceOf)}</StyledValue>
                <Label text="SHARE Staked" color={'#23223E'} />
              </CardSection>
            </StyledCardSuperAccent1>
            {
            <div style={{ marginTop: 30 }}>
              {approveStatus !== ApprovalState.APPROVED ? (
                <Button
                  disabled={
                    approveStatus == ApprovalState.PENDING ||
                    approveStatus == ApprovalState.UNKNOWN
                  }
                  onClick={approve}
                  text={`Approve`}
                />
              ) : (
                <StyledCardActions>
                  <IconButton onClick={onPresentWithdraw}>
                    <RemoveIcon />
                  </IconButton>
                  <StyledActionSpacer />
                  <IconButton
                    onClick={onPresentDeposit}
                  >
                    <AddIcon />
                  </IconButton>
                </StyledCardActions>
              )}
              
            </div>
            }
          </StyledCards>
        </CardWrapper>
        {
        <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
          <div style={{ marginTop: 30 }}>
            {/*
            <ButtonSettle>
              DONATE
            </ButtonSettle>
            */}
            <Button
              disabled={stakedBalance.eq(0)}
              onClick={onDonate}
              text="DONATE"
            />
          </div>
        </div>
        }
        {
        <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
        <DivXiaBack>
          {votes.map((vote, i) => (
            <React.Fragment key={vote.name}>
              <VoteCard vote={vote} />
            </React.Fragment>
          ))}
          {/*
           <BlockTop>
             <p style={{fontSize: 16, color: '#fff', textAlign: 'center', paddingTop: 20}}>
                FLP-001 DAO Roadmap
             </p>
             <BlockSee>
                查看详情
             </BlockSee>
             <BlockRes>
             <img
                src={dui}
                style={{width: 33, height: 'auto'}}
              />

                <BlockText>通过</BlockText>
             </BlockRes>
             <BlockResBottom>
               <BlockShi>
                  <span style={{fontSize:14, color: '#fff',textAlign: 'center'}}>赞同</span>
                  <SpanShi>12345票</SpanShi>
               </BlockShi>
               <BlockShi>
                  <span style={{fontSize:14, color: '#fff',textAlign: 'center'}}>反对</span>
                  <SpanShi>12票</SpanShi>
               </BlockShi>
             </BlockResBottom>
            </BlockTop>
            <BlockTop>
             <p style={{fontSize: 16, color: '#fff', textAlign: 'center', paddingTop: 20}}>
                FLP-001 DAO Roadmap
             </p>
             <BlockSee>
                查看详情
             </BlockSee>
             <BlockRes>
             <img
                src={cuo}
                style={{width: 33, height: 'auto'}}
              />

                <BlockText1>未通过</BlockText1>
             </BlockRes>
             <BlockResBottom>
               <BlockShi>
                  <span style={{fontSize:14, color: '#fff',textAlign: 'center'}}>赞同</span>
                  <SpanFou>12345票</SpanFou>
               </BlockShi>
               <BlockShi>
                  <span style={{fontSize:14, color: '#fff',textAlign: 'center'}}>反对</span>
                  <SpanFou>12票</SpanFou>
               </BlockShi>
             </BlockResBottom>
            </BlockTop>


            <BlockTop>
             <p style={{fontSize: 16, color: '#fff', textAlign: 'center', paddingTop: 20}}>
                FLP-002 DAO Roadmap
             </p>
             <BlockSee>
                查看详情
             </BlockSee>
             <BlockRes>
                <Ingp>投票已开启</Ingp>
                <Ingp>投票后不可撤销或更改</Ingp>

                <DivShiJian>
                  <Ingp style={{marginTop: 5}}>投票已开启</Ingp>
                  <IngTime>12:34:60</IngTime>
                </DivShiJian>
             </BlockRes>
             <BlockResBottom>
               <BlockShi>
                  <span style={{fontSize:14, color: '#fff',textAlign: 'center'}}>赞同</span>
                  <SpanShi>12345票</SpanShi>
                  <ButtonZan>
              赞同
            </ButtonZan>
               </BlockShi>
               <BlockShi>
                  <span style={{fontSize:14, color: '#fff',textAlign: 'center'}}>反对</span>
                  <SpanFou>12票</SpanFou>
                  <ButtonFan>
              反对
            </ButtonFan>
               </BlockShi>
             </BlockResBottom>
            </BlockTop>
          */}

        </DivXiaBack>
        </div>
        }
        </>) : (
          <UnlockWallet />
        )}
      </StylehCont>
    </Page>
  );
};

const UnlockWallet = () => {
  const { connect } = useWallet();
  return (
    <Center>
      <div>
        <Button onClick={() => connect('injected')} text="Unlock Wallet" />
      </div>
    </Center>
  );
};

const StyledActionSpacer = styled.div`
  height: ${(props) => props.theme.spacing[4]}px;
  width: ${(props) => props.theme.spacing[4]}px;
`;

const Center = styled.div`
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
`;

const StyledCards = styled.div`
  width: 205px;
  min-height: 240px;
  margin: 0 15px;
  padding: ${(props) => props.theme.spacing[3]}px 30px;
  color: ${(props) => props.theme.color.white};
  background-color: rgba(48, 55, 78, 0.6);
  @media (max-width: 768px) {
    width: 75%;
    margin: 10px 0px;
    padding: 10px 20px;
  }
`;

const DivXiaBack = styled.div`
background-color: #22223D;
width: 880px;
padding: 50px 20px;
display: flex;
justify-content: space-between;
flex-direction: row;
align-items: center;
flex-wrap: wrap;
@media (max-width: 768px) {
  width: 100%;
  flex-direction: column;
  align-items: center;
  padding: 20px 0px;
}
`

const BlockTop = styled.div`
background-color: #36355E;
width: 220px;
padding: 0px 10px;
display: flex;
min-height: 385px;
flex-direction: column;
@media (max-width: 768px) {
  width: 80%;
  margin-top: 20px;
  justify-content: center;
}
`

const BlockText= styled.div`
  font-size: 16px;
  color: #92E37B;
  text-align: center;
  margin-top: 6px;
`

const BlockText1= styled.div`
  font-size: 16px;
  color: #E85A40;
  text-align: center;
  margin-top: 6px;
`

const BlockRes = styled.div`
  min-height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
`

const DivShiJian = styled.div`
  background-color: #100428;
  width: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
`

const Ingp = styled.p`
  margin: 0;
  padding: 0;
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #7270A0;
  line-height: 22px;
`

const IngTime = styled.p`
  margin: 5px 0;
  padding: 0;
  font-size: 20px;
  font-family: PingFang SC;
  color: #FA4E32;
  line-height: 22px;
`

const BlockResBottom= styled.div`
display: flex;
justify-content: space-between;
padding-bottom: 20px;
`

const ButtonZan  = styled.div`
align-items: center;
background-color: #92E37B;
border: 0;
border-radius: 24px;
color: #000000;
cursor: pointer;
display: flex;
font-size: 15px;
height: 40px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
outline: none;
padding-left: 0px;
padding-right: 0px;
pointer-events: none;
margin-top: 5px;
width: 100px;
`;

const ButtonFan  = styled.div`
align-items: center;
background-color: #E85A40;
border: 0;
border-radius: 20px;
color: #000000;
cursor: pointer;
display: flex;
font-size: 15px;
height: 40px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
outline: none;
padding-left: 0px;
padding-right: 0px;
pointer-events: none;
margin-top: 5px;
width: 100px;
`;

const BlockShi= styled.div`
display: flex;
flex: 1;
flex-direction: column;
justify-content: center;
align-items: center;
`

const SpanShi= styled.span`
  font-size: 16px;
  color: #92E37B;
  text-align: center;
`


const SpanFou= styled.span`
font-size: 16px;
color: #E85A40;
text-align: center;
`

const BlockSee = styled.a`
font-size: 16px;
color: #E95B40;
text-align: center; 
`;


const ButtonSettle = styled.div`
align-items: center;
background-color: #FA4E32;
border: 0;
border-radius: 24px;
color: #000000;
cursor: pointer;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-size: 16px;
height: 56px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
outline: none;
padding-left: 24px;
padding-right: 24px;
pointer-events: none;
width: 175px;
`;


const StyledSupplyLabel = styled.a`
  font-size: 16px;
  display: block;
  color: ${(props) => props.color};
`;


const StyledValue = styled.span`
  display: inline-block;
  font-size: 30px;
  color: #eeeeee;
  margin-bottom: 10px;
`;


const CardSection = styled.div`
  margin-bottom: ${(props) => props.theme.spacing[4]}px;

  &:last-child {
    margin-bottom: 0;
  }
`;

const StyledCardActions = styled.div`
  display: flex;
  justify-content: center;
  margin-top: ${(props) => props.theme.spacing[6]}px;
  width: 100%;
`;

const StyledCardSuperAccent = styled.div`
  background: linear-gradient(180deg, #23233F, #2FEA99);
  margin-top: 25px;
  min-height: 100px;
  border-radius: 0px 0px 20px 20px;
  padding: 20px 20px;
`

const StyledCardSuperAccent1 = styled.div`
  background: linear-gradient(180deg, #23233F, #FA4E32);
  margin-top: 25px;
  min-height: 100px;
  border-radius: 0px 0px 20px 20px;
  padding: 20px 20px;
`

const StyledCardSuperAccent2 = styled.div`
  background: linear-gradient(180deg, #23233F, #318DFF);
  margin-top: 25px;
  min-height: 100px;
  border-radius: 0px 0px 20px 20px;
  padding: 20px 20px;
`


const CardHeader = styled.span`
  font-size: 24px;
  font-family: FZPinShangHeiS-R-GB;
  color: #FFFFFF;
  margin-left: 12px;
`;

const StyleDiv1 = styled.div`
  display: flex;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  max-width: 1300px;
  width: 100%;
  margin: 0 auto;
  z-index: -1;
  // margin-top: -70px;
  @media (max-width: 768px) {
    display: none;
  }
`

const StyleDiv2 = styled.div`
  display: none;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  max-width: 1300px;
  width: 100%;
  margin: 0 auto;
  z-index: -1;
  margin-top: -70px;
  @media (max-width: 768px) {
    display: block;
  }
`

const StylehCont = styled.div`
  background: "#100428"
`;

const Stylesubtitle = styled.p`
color: #FFFFFF;
font-size: 18px;
font-weight: 400;
margin: 0;
padding: 0;
text-align: center;
`

const StyledOverview = styled.div`
  align-items: center;
  display: flex;
  @media (max-width: 768px) {
    width: 100%;
    flex-flow: column nowrap;
    align-items: center;
  }
`;

const CardWrapper = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
  @media (max-width: 768px) {
    width: 100%;
    flex-flow: column nowrap;
    align-items: center;
    margin: 0px 0px;
  }
`;

const CardWrapper1 = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 80%;
  margin-top: 40px;
  @media (max-width: 768px) {
    width: 100%;
    flex-flow: column nowrap;
    align-items: center;
    margin-top: 0px;
  }
`;

const StyledNoticeContainer = styled(Link)`
  opacity: 1;
  cursor: pointer;
  &:hover {
    opacity: 1;
  }
`;

const StyledNoticeContainer1 = styled.div`
  opacity: 0.8;
  cursor: pointer;
  margin-top: 20px;
  &:hover {
    opacity: 1;
  }
  @media (max-width: 768px) {
    margin-top: 0px;
  }
`;

const StyledSpacer = styled.div`
  height: ${(props) => props.theme.spacing[4]}px;
  width: ${(props) => props.theme.spacing[4]}px;
`;

const StyledLink = styled.a`
  font-weight: 700;
  text-decoration: none;
  color: ${(props) => props.theme.color.primary.main};
`;

export default Home;
